# -*- coding: utf-8 -*-
# frontend/pages/04_📈_数据分析.py
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import random
import numpy as np

st.set_page_config(
    page_title="📈 数据分析",
    page_icon="📈",
    layout="wide"
)

def generate_analytics_data():
    """生成模拟分析数据"""
    # 生成过去30天的数据
    dates = [datetime.now() - timedelta(days=i) for i in range(30)]
    dates.reverse()
    
    # 用户活跃度数据
    user_activity = {
        'date': dates,
        'active_users': [random.randint(50, 200) for _ in dates],
        'new_users': [random.randint(5, 30) for _ in dates],
        'messages_sent': [random.randint(100, 500) for _ in dates]
    }
    
    # 模型使用情况
    model_usage = {
        'model': ['GPT-4', '文心一言', '通义千问', 'Claude'],
        'usage_count': [random.randint(500, 2000) for _ in range(4)],
        'avg_response_time': [random.uniform(1.0, 4.0) for _ in range(4)],
        'success_rate': [random.uniform(95, 99.9) for _ in range(4)]
    }
    
    # 话题分析数据
    topic_data = {
        'topic': ['编程技术', '生活建议', '学术研究', '创意写作', '商业咨询', '其他'],
        'count': [random.randint(100, 800) for _ in range(6)],
        'avg_satisfaction': [random.uniform(3.5, 5.0) for _ in range(6)]
    }
    
    return user_activity, model_usage, topic_data

def main():
    st.title("📈 数据分析仪表板")
    st.markdown("---")
    
    # 时间范围选择
    col1, col2, col3 = st.columns([2, 2, 1])
    
    with col1:
        date_range = st.date_input(
            "📅 选择时间范围",
            value=[datetime.now() - timedelta(days=30), datetime.now()],
            max_value=datetime.now()
        )
    
    with col2:
        analysis_type = st.selectbox(
            "📊 分析维度",
            ["综合分析", "用户分析", "模型分析", "话题分析"]
        )
    
    with col3:
        if st.button("🔄 刷新数据", use_container_width=True):
            st.rerun()
    
    # 生成数据
    user_activity, model_usage, topic_data = generate_analytics_data()
    
    if analysis_type == "综合分析":
        render_overview_analysis(user_activity, model_usage, topic_data)
    elif analysis_type == "用户分析":
        render_user_analysis(user_activity)
    elif analysis_type == "模型分析":
        render_model_analysis(model_usage)
    elif analysis_type == "话题分析":
        render_topic_analysis(topic_data)

def render_overview_analysis(user_activity, model_usage, topic_data):
    """渲染综合分析"""
    st.subheader("📊 综合数据概览")
    
    # 关键指标卡片
    metric_col1, metric_col2, metric_col3, metric_col4 = st.columns(4)
    
    with metric_col1:
        total_users = sum(user_activity['active_users'])
        st.metric(
            "👥 总活跃用户", 
            f"{total_users:,}",
            delta=f"+{random.randint(10, 50)}",
            delta_color="normal"
        )
    
    with metric_col2:
        total_messages = sum(user_activity['messages_sent'])
        st.metric(
            "💬 总消息数", 
            f"{total_messages:,}",
            delta=f"+{random.randint(100, 500)}",
            delta_color="normal"
        )
    
    with metric_col3:
        avg_response_time = np.mean(model_usage['avg_response_time'])
        st.metric(
            "⚡ 平均响应时间", 
            f"{avg_response_time:.2f}s",
            delta=f"-{random.uniform(0.1, 0.5):.2f}s",
            delta_color="inverse"
        )
    
    with metric_col4:
        avg_success_rate = np.mean(model_usage['success_rate'])
        st.metric(
            "✅ 平均成功率", 
            f"{avg_success_rate:.1f}%",
            delta=f"+{random.uniform(0.1, 1.0):.1f}%",
            delta_color="normal"
        )
    
    st.markdown("---")
    
    # 趋势图表
    chart_col1, chart_col2 = st.columns(2)
    
    with chart_col1:
        st.subheader("📈 用户活跃度趋势")
        
        df_activity = pd.DataFrame(user_activity)
        
        fig_activity = go.Figure()
        fig_activity.add_trace(go.Scatter(
            x=df_activity['date'],
            y=df_activity['active_users'],
            mode='lines+markers',
            name='活跃用户',
            line=dict(color='#FF6B6B', width=3)
        ))
        fig_activity.add_trace(go.Scatter(
            x=df_activity['date'],
            y=df_activity['new_users'],
            mode='lines+markers',
            name='新用户',
            line=dict(color='#4ECDC4', width=3)
        ))
        
        fig_activity.update_layout(
            xaxis_title="日期",
            yaxis_title="用户数量",
            hovermode='x unified',
            height=400
        )
        
        st.plotly_chart(fig_activity, use_container_width=True)
    
    with chart_col2:
        st.subheader("🤖 模型使用分布")
        
        df_models = pd.DataFrame(model_usage)
        
        fig_models = px.pie(
            df_models,
            values='usage_count',
            names='model',
            title="各模型使用比例",
            color_discrete_sequence=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
        )
        
        fig_models.update_traces(textposition='inside', textinfo='percent+label')
        fig_models.update_layout(height=400)
        
        st.plotly_chart(fig_models, use_container_width=True)
    
    # 详细数据表格
    st.subheader("📋 详细数据")
    
    table_tab1, table_tab2, table_tab3 = st.tabs(["用户数据", "模型数据", "话题数据"])
    
    with table_tab1:
        st.dataframe(pd.DataFrame(user_activity), use_container_width=True)
    
    with table_tab2:
        st.dataframe(pd.DataFrame(model_usage), use_container_width=True)
    
    with table_tab3:
        st.dataframe(pd.DataFrame(topic_data), use_container_width=True)

def render_user_analysis(user_activity):
    """渲染用户分析"""
    st.subheader("👥 用户行为分析")
    
    df_activity = pd.DataFrame(user_activity)
    
    # 用户增长分析
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("#### 📈 用户增长趋势")
        
        fig_growth = go.Figure()
        fig_growth.add_trace(go.Scatter(
            x=df_activity['date'],
            y=df_activity['active_users'].cumsum(),
            mode='lines+markers',
            name='累计用户',
            fill='tonexty',
            line=dict(color='#FF6B6B', width=3)
        ))
        
        fig_growth.update_layout(
            xaxis_title="日期",
            yaxis_title="累计用户数",
            height=400
        )
        
        st.plotly_chart(fig_growth, use_container_width=True)
    
    with col2:
        st.markdown("#### 💬 消息活跃度")
        
        fig_messages = px.bar(
            df_activity,
            x='date',
            y='messages_sent',
            title="每日消息数量",
            color='messages_sent',
            color_continuous_scale='Blues'
        )
        
        fig_messages.update_layout(height=400)
        st.plotly_chart(fig_messages, use_container_width=True)
    
    # 用户画像分析
    st.markdown("#### 👤 用户画像分析")
    
    portrait_col1, portrait_col2, portrait_col3 = st.columns(3)
    
    with portrait_col1:
        st.markdown("**📊 用户类型分布**")
        user_types = ['新手用户', '活跃用户', '专业用户', 'VIP用户']
        user_type_counts = [random.randint(50, 200) for _ in user_types]
        
        fig_user_types = px.pie(
            values=user_type_counts,
            names=user_types,
            color_discrete_sequence=['#FF9999', '#66B2FF', '#99FF99', '#FFD700']
        )
        st.plotly_chart(fig_user_types, use_container_width=True)
    
    with portrait_col2:
        st.markdown("**🕒 使用时间分布**")
        hours = list(range(24))
        usage_by_hour = [random.randint(10, 100) for _ in hours]
        
        fig_hourly = px.bar(
            x=hours,
            y=usage_by_hour,
            labels={'x': '小时', 'y': '使用次数'},
            color=usage_by_hour,
            color_continuous_scale='Viridis'
        )
        st.plotly_chart(fig_hourly, use_container_width=True)
    
    with portrait_col3:
        st.markdown("**📱 设备类型分布**")
        devices = ['桌面端', '移动端', '平板端']
        device_counts = [random.randint(100, 400) for _ in devices]
        
        fig_devices = px.pie(
            values=device_counts,
            names=devices,
            color_discrete_sequence=['#FF6B6B', '#4ECDC4', '#45B7D1']
        )
        st.plotly_chart(fig_devices, use_container_width=True)

def render_model_analysis(model_usage):
    """渲染模型分析"""
    st.subheader("🤖 模型性能分析")
    
    df_models = pd.DataFrame(model_usage)
    
    # 模型性能对比
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("#### ⚡ 响应时间对比")
        
        fig_response = px.bar(
            df_models,
            x='model',
            y='avg_response_time',
            color='avg_response_time',
            color_continuous_scale='RdYlGn_r',
            text='avg_response_time'
        )
        
        fig_response.update_traces(texttemplate='%{text:.2f}s', textposition='outside')
        fig_response.update_layout(
            yaxis_title="平均响应时间 (秒)",
            height=400
        )
        
        st.plotly_chart(fig_response, use_container_width=True)
    
    with col2:
        st.markdown("#### ✅ 成功率对比")
        
        fig_success = px.bar(
            df_models,
            x='model',
            y='success_rate',
            color='success_rate',
            color_continuous_scale='RdYlGn',
            text='success_rate'
        )
        
        fig_success.update_traces(texttemplate='%{text:.1f}%', textposition='outside')
        fig_success.update_layout(
            yaxis_title="成功率 (%)",
            height=400
        )
        
        st.plotly_chart(fig_success, use_container_width=True)
    
    # 模型详细分析
    st.markdown("#### 📊 模型综合评分")
    
    # 计算综合评分
    df_models['performance_score'] = (
        (df_models['usage_count'] / df_models['usage_count'].max() * 0.3) +
        ((5 - df_models['avg_response_time']) / 5 * 0.4) +
        (df_models['success_rate'] / 100 * 0.3)
    ) * 100
    
    fig_radar = go.Figure()
    
    for i, model in enumerate(df_models['model']):
        fig_radar.add_trace(go.Scatterpolar(
            r=[
                df_models.iloc[i]['usage_count'] / df_models['usage_count'].max() * 100,
                (5 - df_models.iloc[i]['avg_response_time']) / 5 * 100,
                df_models.iloc[i]['success_rate'],
                df_models.iloc[i]['performance_score']
            ],
            theta=['使用频率', '响应速度', '成功率', '综合评分'],
            fill='toself',
            name=model
        ))
    
    fig_radar.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 100]
            )
        ),
        showlegend=True,
        height=500
    )
    
    st.plotly_chart(fig_radar, use_container_width=True)

def render_topic_analysis(topic_data):
    """渲染话题分析"""
    st.subheader("🏷️ 话题趋势分析")
    
    df_topics = pd.DataFrame(topic_data)
    
    # 话题热度分析
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("#### 🔥 话题热度排行")
        
        fig_topic_count = px.bar(
            df_topics.sort_values('count', ascending=True),
            x='count',
            y='topic',
            orientation='h',
            color='count',
            color_continuous_scale='plasma',
            text='count'
        )
        
        fig_topic_count.update_traces(textposition='outside')
        fig_topic_count.update_layout(
            xaxis_title="讨论次数",
            height=400
        )
        
        st.plotly_chart(fig_topic_count, use_container_width=True)
    
    with col2:
        st.markdown("#### ⭐ 话题满意度")
        
        fig_satisfaction = px.scatter(
            df_topics,
            x='count',
            y='avg_satisfaction',
            size='count',
            color='avg_satisfaction',
            hover_name='topic',
            color_continuous_scale='RdYlGn',
            size_max=60
        )
        
        fig_satisfaction.update_layout(
            xaxis_title="讨论次数",
            yaxis_title="平均满意度",
            height=400
        )
        
        st.plotly_chart(fig_satisfaction, use_container_width=True)
    
    # 话题词云（模拟）
    st.markdown("#### ☁️ 话题词云分析")
    
    # 模拟词云数据
    word_cloud_data = {
        'word': ['Python', 'AI', '机器学习', '深度学习', '数据分析', '算法', '编程', '技术', '项目', '代码',
                '生活', '建议', '工作', '学习', '经验', '思考', '创意', '写作', '故事', '诗歌'],
        'frequency': [random.randint(50, 300) for _ in range(20)],
        'sentiment': [random.choice(['positive', 'neutral', 'negative']) for _ in range(20)]
    }
    
    df_words = pd.DataFrame(word_cloud_data)
    
    # 用气泡图模拟词云效果
    fig_wordcloud = px.scatter(
        df_words,
        x=[random.uniform(-10, 10) for _ in range(20)],
        y=[random.uniform(-10, 10) for _ in range(20)],
        size='frequency',
        color='sentiment',
        hover_name='word',
        hover_data=['frequency'],
        color_discrete_map={
            'positive': '#00CC96',
            'neutral': '#636EFA', 
            'negative': '#EF553B'
        },
        size_max=80
    )
    
    fig_wordcloud.update_layout(
        showlegend=True,
        xaxis=dict(showgrid=False, showticklabels=False, title=""),
        yaxis=dict(showgrid=False, showticklabels=False, title=""),
        height=500
    )
    
    st.plotly_chart(fig_wordcloud, use_container_width=True)
    
    # 话题趋势预测
    st.markdown("#### 🔮 话题趋势预测")
    
    trend_col1, trend_col2 = st.columns(2)
    
    with trend_col1:
        st.markdown("**📈 上升趋势话题**")
        rising_topics = [
            {"topic": "🤖 ChatGPT应用", "growth": "+245%"},
            {"topic": "🎨 AI绘画", "growth": "+189%"},
            {"topic": "💻 代码生成", "growth": "+156%"},
            {"topic": "📊 数据可视化", "growth": "+98%"}
        ]
        
        for topic_info in rising_topics:
            st.markdown(f"""
            <div style="
                background: linear-gradient(90deg, #00CC9622 0%, #00CC9611 100%);
                border-left: 4px solid #00CC96;
                padding: 10px;
                margin: 5px 0;
                border-radius: 5px;
            ">
                <strong>{topic_info['topic']}</strong><br>
                <span style="color: #00CC96; font-weight: bold;">{topic_info['growth']}</span>
            </div>
            """, unsafe_allow_html=True)
    
    with trend_col2:
        st.markdown("**📉 下降趋势话题**")
        declining_topics = [
            {"topic": "📱 传统编程", "decline": "-23%"},
            {"topic": "🖥️ 桌面应用", "decline": "-18%"},
            {"topic": "💿 系统运维", "decline": "-12%"},
            {"topic": "🌐 Web前端", "decline": "-8%"}
        ]
        
        for topic_info in declining_topics:
            st.markdown(f"""
            <div style="
                background: linear-gradient(90deg, #EF553B22 0%, #EF553B11 100%);
                border-left: 4px solid #EF553B;
                padding: 10px;
                margin: 5px 0;
                border-radius: 5px;
            ">
                <strong>{topic_info['topic']}</strong><br>
                <span style="color: #EF553B; font-weight: bold;">{topic_info['decline']}</span>
            </div>
            """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()